<?php

/**
 * <pre>
 * if($handler =  Event::load($action))
 * {
 * 	Event::emit($handlers, $action,	$subject, $params);
 * }
 * </pre>
 */
class Hook
{

	/**
	 * @var array
	 */
	static protected $_hooks = null;
	
	/**
	 * @bool
	 */
	static protected $_initilized = false;

	static public function __init()
	{
		if (self::$_initilized)
		{
			return;
		}

		$key = 'agilet.hooks';

		$cache = Cache::instance();

		$data = array();

		if (FALSE == ($data = $cache -> get($key)))
		{
			$table = Model::getTable('core/hook');

			$select = $table -> select() -> where('is_active=1') -> order('sort_order');

			$rows = $table -> fetchAll($select);

			foreach ($rows as $row)
			{
				$plugin = $row -> getPlugin();

				if (strpos($plugin, ':'))
				{
					list($plugin, $action) = explode(':', $plugin);
				}
				$data[$row -> getAction()][$plugin] = $action;
			}

			$cache -> set($key, $data);
		}
		self::$_initilized = true;

		self::$_hooks = $data;
	}

	/**
	 * @param string $action
	 * @return array/FALSE
	 */
	static public function load($action)
	{
		self::$_initilized or self::__init();

		if (isset(self::$_hooks[$action]))
		{
			return self::$_hooks[$action];
		}
		return FALSE;
	}

	static public function emit($hooks, $action, $param_arr = null)
	{

		if (!$hooks)
		{
			return;
		}

		$param_arr = (array)$param_arr;

		foreach ($hooks as $plugin => $action)
		{
			try
			{
				$obj = Agilet::getPlugin($plugin);

				call_user_func_array(array(
					$obj,
					$action
				), $param_arr);
			}
			catch(Exception $exception)
			{
				Agilet::__exceptionHandler($exception);
			}
		}
	}

}
